import { getElement, getScale } from "./ecgPublic";

export default function () {
  let ctx = null
  const clearRubbish = 10

  // 画时间
  const draw = async (params) => {
    const {
      element,
      gridScale = 1,
      dpr = getScale(true), //屏幕缩放比
      ppm = 4,
      fontSize = 11, // 字体大小
      lineColor = '#000000',// 线条色
      fontColor = "#333333", // 字体色
      isDrawFlag = true, // 是否开启画时间
      canvasWidth = 0,
      speed = 25,
      dynamicTime = 0,
      canvasHeight = 0
    } = params
    let canvasElement = await getElement(element)
    const canvas = canvasElement?.node
    if (!canvas) return
    const width = canvasElement.width
    const height = canvasElement.height
    canvas.width = canvasWidth * dpr
    canvas.height = height * dpr
    ctx = canvas.getContext('2d')
    if (!ctx) { return false }
    ctx.beginPath()

    ctx.clearRect(
      0 - clearRubbish,
      0 - clearRubbish,
      width + clearRubbish,
      height + clearRubbish,
    )
    ctx.stroke()
    ctx.scale(dpr, dpr)

    // 画时间段
    if (isDrawFlag) {
      drawTimes({ ppm, canvasWidth, gridScale, fontSize, fontColor, lineColor, dynamicTime, canvasHeight, speed });
    }

  }


  // 每个时间间隔长度(后续需要计算)
  const drawTimes = (params) => {
    const { ppm, canvasWidth, gridScale, fontSize, fontColor, lineColor, dynamicTime, canvasHeight, speed } = params
    const difference = 1 / (speed / 25)
    let timeVal = 0
    // 起始位置
    const startX = 1;
    for (let drawX = startX; drawX < canvasWidth - ppm * 6; drawX += ppm * 5 * 5) {
      ctx.font = `600 ${fontSize / gridScale}px Microsoft YaHei`;
      ctx.fillStyle = fontColor;
      ctx.strokeStyle = lineColor;
      ctx.textAlign = "left";
      ctx.textBaseline = "bottom";
      ctx.fillText(
        `${(timeVal + dynamicTime).toFixed(1)}s`,
        drawX,
        canvasHeight - 2
      );
      timeVal += difference;
    }
  };



  return {
    draw
  }
}
